<template>
  <el-dialog ref="el-dialog" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false" style="padding-bottom: 15vh;" :before-close="close">
    <template slot="title">
      <div class="titleDiv">
        <div class="titleDivOne">{{ isEdit ? '编辑' : '新增' }}控制器</div>
      </div>
    </template>
    <div>
      <el-form ref="RefForm" :model="formData" label-width="100px" :validate-on-rule-change="false" :rules="formRules" status-icon>
        <div class="bigBox">
          <div class="divOne">
            <el-form-item label="控制器名称" prop="name">
              <el-input v-model="formData.name" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="区域" prop="areaId">
              <el-select v-model="formData.areaId" style="width: 100%;" placeholder="请选择">
                <el-option v-for="item in region" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序列号" prop="serialNo">
              <el-input v-model="formData.serialNo" maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="IP地址">
              <el-input v-model="formData.ip" maxlength="30" show-word-limit></el-input>
            </el-form-item>
            <!-- <el-form-item label="坐标X" prop="xPosition">
              <el-input v-model="formData.xPosition" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="坐标Y" prop="yPosition">
              <el-input v-model="formData.yPosition" maxlength="10" show-word-limit></el-input>
            </el-form-item>-->
            <el-form-item label="闸机范围宽度" prop="widthPosition">
              <el-input v-model="formData.widthPosition" type="number" step="10" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="闸机范围高度" prop="heightPosition">
              <el-input v-model="formData.heightPosition" type="number" step="10" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="范围距离左侧" prop="leftPosition">
              <el-input v-model="formData.leftPosition" type="number" step="10" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="范围距离顶部" prop="topPosition">
              <el-input v-model="formData.topPosition" type="number" step="10" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="范围旋转角度" prop="rotate">
              <el-input v-model="formData.rotate" type="number" step="10" maxlength="10" show-word-limit></el-input>
            </el-form-item>
            <div class="dialog-button">
              <el-button @click="close">取 消</el-button>
              <el-button :loading="loadingSubmit" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
          </div>
          <div id="map" class="divTwo" @click="getCoordinateHandler">
            <div
              class="rangeDiv"
              :style="{ left: formData.leftPosition / 1.5 + 'px', top: formData.topPosition / 1.5 + 'px', width: formData.widthPosition / 1.5 + 'px', height: formData.heightPosition / 1.5 + 'px', transform: 'rotateZ(' + formData.rotate + 'deg)' }"
            ></div>
            <!-- 基站 -->
            <template v-for="item in baseStationList">
              <el-popover
                :key="item.id"
                placement="top-start"
                class="up"
                :style="{ left: item.x / 1.5 + 'px', top: item.y / 1.5 + 'px', zIndex: 10 }"
                trigger="hover"
              >
                <div class="labelDiv">
                  <span class="shallow">基站名称:</span>
                  <span class="deep">{{ item.name }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">基站类型:</span>
                  <span class="deep">{{ item.siteType }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">区域:</span>
                  <span class="deep">{{ item.areaName }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">状态:</span>
                  <span class="deep">{{ item.status }}</span>
                </div>
                <!-- <div class="labelDiv">
                  <span class="shallow">考勤机站:</span>
                  <span class="deep">{{ item.isForWorkCheck ? '是' : '否' }}</span>
                </div> -->
                <img slot="reference" :src="iconData[0].value" alt="基站" />
              </el-popover>
            </template>
            <!-- 基站覆盖范围 -->
            <template v-for="baseStation in baseStationList">
              <el-popover
                :key="baseStation.name"
                placement="top-start"
                class="range"
                :style="{ width: baseStation.widthPosition / 1.5 + 'px', height: baseStation.heightPosition / 1.5 + 'px', transform: 'rotateZ(' + baseStation.rotate + 'deg)', left: baseStation.leftPosition / 1.5 + 'px', top: baseStation.topPosition / 1.5 + 'px' }"
                trigger="hover"
              >
                <div class="labelDiv">
                  <span class="shallow">范围归属:</span>
                  <span class="deep">{{ baseStation.name }}</span>
                </div>
                <div
                  slot="reference"
                  :style="{ width: baseStation.widthPosition / 1.5 + 'px', height: baseStation.heightPosition / 1.5 + 'px', border: 'none' }"
                  class="range"
                ></div>
              </el-popover>
            </template>
            <!-- 监控设备 -->
            <el-popover
              v-for="cameraItem in videoList"
              :key="cameraItem.id"
              placement="top-start"
              class="cameraItem"
              :style="{ left: cameraItem.x / 1.5 + 'px', top: cameraItem.y / 1.5 + 'px' }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">监控名称:</span>
                <span class="deep">{{ cameraItem.name }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">区域:</span>
                <span class="deep">{{ cameraItem.area ? cameraItem.area.name : '无' }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">状态:</span>
                <span class="deep">{{ cameraItem ? cameraItem.status : '' }}</span>
              </div>
              <img slot="reference" :src="iconData[1].value" alt="监控" />
            </el-popover>
            <!-- 闸机覆盖范围 -->
            <template v-for="gatesItem in gatesList">
              <el-popover
                v-if="gatesItem.serialNo != formData.serialNo"
                :key="gatesItem.id"
                placement="top-start"
                class="range"
                :style="{ width: gatesItem.widthPosition / 1.5 + 'px', height: gatesItem.heightPosition / 1.5 + 'px', transform: 'rotateZ(' + gatesItem.rotate + 'deg)', left: gatesItem.leftPosition / 1.5 + 'px', top: gatesItem.topPosition / 1.5 + 'px' }"
                trigger="hover"
              >
                <div class="labelDiv">
                  <span class="shallow">范围归属:</span>
                  <span class="deep">{{ gatesItem.name }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">闸机类型:</span>
                  <span class="deep">{{ gatesItem.siteType }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">区域:</span>
                  <span class="deep">{{ gatesItem.areaName }}</span>
                </div>
                <div
                  slot="reference"
                  :style="{ width: gatesItem.widthPosition / 1.5 + 'px', height: gatesItem.heightPosition / 1.5 + 'px', border: 'none' }"
                  class="range"
                ></div>
              </el-popover>
            </template>
            <!-- 环境监测设备 -->
            <template v-for="environmentalItem in environmentalList">
              <el-popover
                :key="environmentalItem.id"
                placement="top-start"
                class="cameraItem"
                :style="{ left: environmentalItem.x / 1.5 + 'px', top: environmentalItem.y / 1.5 + 'px' }"
                trigger="hover"
              >
                <div class="labelDiv">
                  <span class="shallow">监测设备:</span>
                  <span class="deep">{{ environmentalItem.name }}</span>
                </div>
                <div class="labelDiv">
                  <span class="shallow">设备IP:</span>
                  <span class="deep">{{ environmentalItem.ip }}</span>
                </div>
                <template v-if="environmentalItem.settingItems.length > 0">
                  <div v-for="(project, projectIndex) in environmentalItem.settingItems" :key="project.key" class="labelDiv">
                    <span v-if="projectIndex === 0" class="shallow">监测项目:</span>
                    <span v-else class="shallowTwo"></span>
                    <span class="deep">{{ project.key ? project.key : '无' }}；</span>
                  </div>
                </template>
                <template v-else>
                  <div class="labelDiv">
                    <span class="shallow">监测项目:</span>
                    <span class="deep">无</span>
                  </div>
                </template>
                <img slot="reference" :src="iconData[2].value" alt="环境监测设备" />
              </el-popover>
            </template>
            <img v-if="mapSwaitch" class="mapImg" :src="imgSrc + mapUrl" alt />
            <img v-else class="mapImg" :src="mapUrl" alt />
          </div>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
  import dialogEditMixin from '@/mixins/dialogEdit'
  import { eleValidator } from '@/utils/tools'
  import { assetsImages } from '@/utils/images'
  import { area, tunnel, parameter, tunnelRealTime } from '@/api/api'
  import { localhostUrl } from '@/utils/setUrl.js'
  export default {
    mixins: [dialogEditMixin],
    data() {
      return {
        region: [],
        formRules: {
          name: [
            { required: true, message: '请输入控制器名称', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '控制器名称不能为空' },
                { rule: 'isRepeat', msg: { value: '控制器名称重复', url: '/AutoGate/Exists', key: 'name' } }
              ]),
              trigger: 'blur'
            }
          ],
          // 区域ID
          areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
          serialNo: [
            { required: true, message: '请输入序列号', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '序列号不能为空' },
                { rule: 'isRepeat', msg: { value: '序列号重复', url: '/AutoGate/Exists', key: 'serialNo' } }
              ]),
              trigger: 'blur'
            }
          ]
        },
        imgUrl: '',
        mapUrl: '',
        imgSrc: localhostUrl + '/',
        mapSwaitch: true,
        // 地图：单洞
        singleHole: assetsImages.singleHole,
        // 地图：双洞
        doubleHole: assetsImages.doubleHole,
        // 闸机
        gatesList: [],
        // 监控
        videoList: [],
        // 基站
        baseStationList: [],
        // 图标数据
        iconData: [
          { name: 'BaseStationImage', value: '', id: null }, // 基站
          { name: 'MonitorImage', value: '', id: null }, // 监控
          { name: 'AccessControlImage', value: '', id: null } // 环境监测设备
        ],
        // 环境检测设备
        environmentalList: []
      }
    },
    watch: {
      dialogVisible: function (newValue, oldValue) {
        if (newValue) {
          return
        }

        this.$refs.RefForm.clearValidate()
      }
    },
    methods: {
      // 请求区域数据
      async getAreaList() {
        try {
          const obj = { pageIndex: 1, pageSize: 1e8 }
          const {
            data: { items: resData }
          } = await area('post', obj, false)
          const regionData = resData.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
          this.$nextTick(() => {
            this.region = regionData
          })
        } catch (err) {
          this.region = []
        }
      },
      resetFormData() {
        this.formData = {
          ip: '',
          name: '', // 名称
          areaId: '',
          serialNo: '', // 序列号
          // xPosition: 0, // 坐标X
          // yPosition: 0, // 坐标Y
          // 范围宽度
          widthPosition: '',
          // 范围高度
          heightPosition: '',
          // 范围距离左侧
          leftPosition: '',
          // 范围距离顶部
          topPosition: '',
          // 旋转角度
          rotate: ''
        }
      },
      // 获取隧道示意图
      async getTunnelData() {
        try {
          this.getAreaList()
          let obj = { id: 1 }
          let res = await tunnel('get', obj, true)
          if (res.code === 200) {
            if (res.data.useTemplate) {
              if (res.data.templateName === '单洞') {
                this.mapUrl = this.singleHole
              } else if (res.data.templateName === '双洞') {
                this.mapUrl = this.doubleHole
              }
              this.mapSwaitch = false
            } else {
              this.mapSwaitch = true
              this.mapUrl = res.data.backedImageName
            }
          }
        } catch (err) {
          // this.$message.error('隧道示意图查询失败！')
        }
      },
      // 基站图片
      async getBaseStationImage() {
        try {
          let res = await parameter('get', { parameterName: 'BaseStationImage' })
          if (res.code === 200) {
            this.iconData[0].value = res.data.value
            this.iconData[0].id = res.data.id
          }
        } catch (err) {
          // 基站图片
          this.iconData[0].value = assetsImages.baseStation
          // this.$message.error('基站图标查询失败，已使用默认图标！')
        }
      },
      // 监控图片
      async getMonitorImage() {
        try {
          let res = await parameter('get', { parameterName: 'MonitorImage' })
          if (res.code === 200) {
            this.iconData[1].value = res.data.value
            this.iconData[1].id = res.data.id
          }
        } catch (err) {
          // 监控设备
          this.iconData[1].value = assetsImages.camera
          // this.$message.error('监控图标查询失败，已使用默认图标！')
        }
      },
      // 环境监测设备图片
      async getAccessControlImage() {
        try {
          let res = await parameter('get', { parameterName: 'AccessControlImage' })
          if (res.code === 200) {
            this.iconData[2].value = res.data.value
            this.iconData[2].id = res.data.id
          }
        } catch (err) {
          // 环境监测图片
          this.iconData[2].value = assetsImages.sensor
        }
      },
      // 请求图标
      async getIcon() {
        this.imgUrl = assetsImages.gate
        await this.getBaseStationImage()
        await this.getMonitorImage()
        await this.getAccessControlImage()
      },
      // 请求其他设备
      async getEquipment() {
        try {
          let resList = await tunnelRealTime()
          // 处理基站数据
          this.handleBaseStation(resList.data.baseStation)
          // 处理监控数据
          this.handleVedioData(resList.data.videos)
          // 门禁闸机
          this.handleGates(resList.data.gates)
          // 环境检测设备
          this.handleEnvironmental(resList.data.environmentTrackings)
        } catch (err) {
          let er = err
        }
      },
      // 基站
      handleBaseStation(value) {
        if (value.lenght === 0) {
          return
        }
        // 获取基站数据
        this.baseStationList = value.map((item, index) => {
          return {
            name: item.name,
            id: index + 'a',
            x: item.xPosition,
            y: item.yPosition,
            status: item.status,
            areaName: item.area ? item.area.name : '无',
            siteType: item.siteType === 1 ? '进基站' : item.siteType === 2 ? '出基站' : '其它基站',
            isForWorkCheck: item.isForWorkCheck,
            // 基站范围宽度
            widthPosition: item.widthPosition,
            // 基站范围高度
            heightPosition: item.heightPosition,
            // 基站范围左侧距离
            leftPosition: item.leftPosition,
            // 基站范围顶部距离
            topPosition: item.topPosition,
            // 基站范围旋转角度
            rotate: item.rotate
          }
        })
      },
      // 门禁闸机
      handleGates(value) {
        if (value.lenght === 0) {
          return
        }
        // 获取闸机数据
        this.gatesList = value.map(item => {
          return {
            name: item.name,
            x: item.xPosition,
            y: item.yPosition,
            serialNo: item.serialNo,
            areaName: item.area ? item.area.name : '无',
            siteType: item.siteType === 1 ? '进基站' : item.siteType === 2 ? '出基站' : '其它基站',
            isForWorkCheck: item.isForWorkCheck,
            // 基站范围宽度
            widthPosition: item.widthPosition,
            // 基站范围高度
            heightPosition: item.heightPosition,
            // 基站范围左侧距离
            leftPosition: item.leftPosition,
            // 基站范围顶部距离
            topPosition: item.topPosition,
            // 基站范围旋转角度
            rotate: item.rotate
          }
        })
      },
      // 处理监控
      handleVedioData(value) {
        if (value.lenght === 0) {
          return
        }
        this.videoList = value.map(item => {
          return item
        })
      },
      // 环境检测设备
      handleEnvironmental(value) {
        if (value.lenght === 0) {
          return
        }
        this.environmentalList = value.map((item, index) => {
          return {
            name: item.name,
            x: item.x,
            y: item.y,
            id: item.id + 'b',
            ip: item.ip,
            code: item.code,
            settingItems: item.settingItems // 监测项
          }
        })
      },
      // 取随机数
      random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
      },
      getCoordinateHandler(event) {
        let map = document.querySelector('#map')
        let dialog = this.$refs['el-dialog']
        // 获取鼠标在浏览器中的位置
        let mousex = event.clientX
        let mousey = event.clientY
        // 获取盒子位置
        let elementx = map.offsetLeft + dialog.$refs.dialog.offsetLeft
        let elementy = map.offsetTop + dialog.$refs.dialog.offsetTop - dialog.$el.scrollTop
        // 获取鼠标在盒子中的位置
        this.formData.xPosition = (mousex - elementx) * 1.5
        this.formData.yPosition = (mousey - elementy) * 1.5
      }
    }
  }
</script>

<style lang="scss" scoped>
  .labelDiv {
    display: flex;
    .deep {
      color: #000;
      // width: 120px;
      text-align: left;
    }
    .shallow {
      padding-right: 10px;
      color: #666;
      width: 70px;
      text-align: right;
    }
    .shallowTwo {
      display: inline-block;
      width: 70px;
      height: 100%;
      text-align: right;
    }
  }
  .bigBox {
    display: flex;
    .divOne {
      flex: 1;
      .el-input {
        min-width: 170px;
      }
      .dialog-button {
        width: 100%;
        text-align: center;
      }
    }
    .divTwo {
      min-width: 802px;
      max-width: 802px;
      height: 402px;
      margin-left: 20px;
      border: 1px solid #ccc;
      position: relative;
      background-color: #ccc;
      .mapImg {
        width: 100%;
        height: 100%;
      }
      .divS {
        width: 20px;
        height: 20px;
        display: none;
        position: absolute;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        background-color: #fff;
        img {
          width: 100%;
          height: 100%;
          float: left;
        }
      }
      .rangeDiv {
        position: absolute;
        border: 1px solid #4682b4;
      }
      .range {
        display: inline-block;
        position: absolute;
        border: 1px solid lime;
      }
      .up {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        position: absolute;
        display: inline-block;
        background-color: #fff;
        transform: translate(-50%, -50%);
        img {
          float: left;
          width: 100%;
          height: 100%;
        }
      }
      .cameraItem {
        z-index: 100;
        width: 20px;
        height: 20px;
        left: 0;
        top: 0;
        border-radius: 50%;
        position: absolute;
        display: inline-block;
        background-color: #fff;
        img {
          width: 100%;
          height: 100%;
          float: left;
        }
      }
    }
  }
</style>
